package handlers

import (
	"encoding/json"
	"news-info-sys/cache"
	"news-info-sys/models"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var news []models.News
	redis_key := "list_page" + strconv.Itoa(page)
	cax, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cax == "" {
		models.DB.Offset(offset).Limit(size).Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte("cax"), &news)
	}
	var total int64
	models.DB.Model(&models.News{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  news,
		"total": total,
	})
}
func Create(c *gin.Context) {
	title := c.PostForm("title")
	info := c.PostForm("info")
	picture := c.PostForm("picture")
	form := c.PostForm("form")
	data := models.News{
		Title:   title,
		Info:    info,
		Picture: picture,
		Form:    form,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
